<template>
  <div class="container">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="视频名称" prop="title">
        <el-input v-model="form.title" size="mini" class="iptFormLen"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="pic">
    
      </el-form-item>
      <el-form-item label="选择视频" prop="video">
        
          <p class="v-des">请上传mp4格式，且不超过500M</p>
          <div class="video-list">
            <p class="v-des" v-for="(item, key, index) in fileList">
              <span>{{ item.name }}</span><!--<span style="margin-left:10px;color:#bbb;">{{item.size}}M</span>-->
              <i class="el-icon-close" @click="delVideo" v-if="fileList.length > 0"></i>
              <i class="el-icon-circle-check"  v-if="fileList.length > 0"></i>
            </p><!-- v-if="percent<1 && percent>0"-->
            <p class="barProg">
              <img class="progress" :width="progressBar">
            </p>
          </div>
      </el-form-item>
    <!--   <el-form-item label="简介" prop="desc">
        <el-input placeholder="请输入简介" v-model="form.desc" name="desc" class="iptFormLen itemLeft"></el-input>
      </el-form-item> -->

      <div class="switch-lang">以下请填写对应英文版本：</div>

      <el-form-item label="视频名称" prop="title_en">
        <el-input v-model="form.title_en" size="mini" class="iptFormLen"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="pic_en">
        <!-- <upload-img :options="myOption" v-on:getPictureUrl="myPicUrl_en"></upload-img> -->
      </el-form-item>
      <el-form-item label="选择视频" prop="video_en">
          <div class="v-upload-btn">
            <el-button size="mini" type="primary">点击上传</el-button>
            <input type="file" id="uploadVideo_en" accept="*" @change="uploadVideo_en" class="file">
          </div>
          <p class="v-des">请上传mp4格式，且不超过500M</p>
          
          <div class="video-list">
            <p class="v-des" v-for="(item, key, index) in fileList_en">
              <span>{{ item.name }}</span><!--<span style="margin-left:10px;color:#bbb;">{{item.size}}M</span>-->
              <i class="el-icon-close" @click="delVideo_en" v-if="fileList_en.length > 0"></i>
              <i class="el-icon-circle-check"  v-if="fileList_en.length > 0"></i>
            </p><!-- v-if="percent<1 && percent>0"-->
            <p class="barProg">
              <img class="progress" :width="progressBar_en">
            </p>
          </div>
      </el-form-item>
 <!--      <el-form-item label="简介" prop="desc_en">
        <el-input placeholder="请输入简介" v-model="form.desc_en" name="desc_en" class="iptFormLen itemLeft"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="submit('form')" size="mini">保 存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  // import uploadImg from '../../../component/upload/uploadLR.vue'
  import {pluginService} from '../../service/pluginService'
  // import {contentService} from '../../../service/contentService'
  let myEditor;// 富文本编辑器
  let myEditor_en;// 富文本编辑器
  export default {
    props: [],
    data () {
      return {
        form: {
          title: '', // 名称
          title_en: '', // 名称
          pic: '', // 图片
          pic_en: '', // 图片
          video: '', // 视频
          video_en: '', // 视频
          desc: '', //简介
          desc_en: '' //简介
        }, // 新增表单
        rules: {
          title: [
            { required: true, message: '请输入演示视频名称', trigger: 'blur' },
            { min: 0, max: 30, message: '长度在30个字符以内', trigger: 'blur' }
          ],
          pic: [
            { required: true, message: '请上传演示视频图片', trigger: 'blur' },
          ],
          video: [
            { required: true, message: '请上传演示视频', trigger: 'blur' },
          ],
          desc: [
            { required: true, message: '请输入简介', trigger: 'blur' }
          ]
        }, //表单验证
          progressBar: 0,
          progressBar_en: 0,
        fileList: [],
        fileList_en: [],
        ossOption: { // oss上传视频
            region: 'oss-cn-shanghai',
            accessKeyId: '',
            accessKeySecret: '',
            stsToken: '',
            bucket: 'well-tour'
        },
        myOption: {
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: 900,
          autoCropHeight: 600,
          // 开启宽度和高度比例
          fixedNumber: [3, 2],
          // 描述文字一
          des: '建议尺寸为900*600，不大于2m，支持.png .jpg .jpeg',
          // 描述文字二
          des2: '说明：该图片将显示在活动列表页，用于向用户直观传达该活动的内容。'
        } //截图

      }
    },
    // components: {'upload-img': uploadImg},
    mounted () {
      let that = this;
      // that.editor(); // 初始化富文本编辑器
      that.getYunToken(); // 得到阿里云token
    },
    methods: {
      // 表单提交
      submit (form) {
        let that = this;
        that.form.desc = myEditor.getData();
        that.form.desc_en = myEditor_en.getData();
        // 表单验证
        this.$refs[form].validate((valid) => {
          if (valid) { //验证成功
            //console.log('tijiao', that.form);
            contentService.addVideoDemo({
                name: that.form.title,
                name_en: that.form.title_en,
                cover: that.form.pic,
                cover_en: that.form.pic_en,
                video: that.form.video,
                video_en: that.form.video_en,
                description: that.form.desc,
                description_en: that.form.desc_en}).then(function (res) {
                  //console.log('submit success', res);
                  if(res.data.success){
                      that.$router.push({name: 'videoDemo'});
                  }
            });
          } else {
            //console.log('error submit!!');
            return false;
          }
        });
      },
      // 图片上传
      myPicUrl (val) {
        let that = this;
        that.form.pic = val;// 封面图
      },
      // 图片上传
      myPicUrl_en (val) {
        let that = this;
        that.form.pic_en = val;// 封面图
      },
 
      // 视频上传
      uploadVideo_en (event) {
        let that = this;
        console.log(1)

        let e = event || window.event;
        let file = e.target.files[0];
        let fileName = file.name;
        let limit = parseFloat(file.size / 1024 / 1024) ; //  kb=file.size / 1024; mb= file.size / 1024 / 1024;
        let key ='video/'+that.getNowFormatDate()+'/'+ file.name; // 新文件名称
        let  suffix = file.name.substr(file.name.lastIndexOf(".")).toLowerCase(); // 文件后缀名
          // 只可以上传一个视频
        if(that.fileList_en.length >= 1){
            this.$alert('只可以上传一个视频', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
            });
            return false;
        }
        // 请上传mp4格式的视频
        // if(suffix!='.mp4'){
        //     this.$alert('请上传MP4格式的视频', '提示', {
        //         confirmButtonText: '确定',
        //         callback: action => {
        //         }
        //     });
        //     return false;
        // }
        // 视频小于500mb
        if(limit < 500){
            let client = new OSS.Wrapper(that.ossOption);
            // 上传
            // console.log(file)
            client.multipartUpload(key, file, {

                // progress: function* (percentage, cpt) {
                      // 上传进度
                    // that.progressBar_en = percentage*100 + '%';
                //    console.log('percentage', percentage);
                //    console.log('cpt', cpt);
                  progress (done) {
                     that.progressBar_en = done*100 + '%';
                       return function (done) {
                           done();
                         };
                     },
                // }
            }).then((results) => {
                // 上传完成
                console.log(results)
                console.log(results,'上传完成');
                that.form.video_en = "http://well-tour.oss-cn-shanghai.aliyuncs.com/"+key;
                  let option = {
                    name: fileName,
                    size: Math.floor(limit),
                  }
                  that.fileList_en.push(option);
            }).catch((err) => {

                console.log("错误：" + err)
            });
          // var obj = document.getElementById("uploadVideo_en") ;
          // obj.outerHTML = obj.outerHTML;
        }else{
           // 不超过500m
            this.$alert('上传视频的大小不能超过500mb', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
            });
        }
      },
      getYunToken () { // 获取阿里云token
          let that = this;
          pluginService.getYunToken().then(function (res) {
             //console.log('获取阿里云token', res);

              if(res.data.success){

                  let info = res.data.datas;
                  that.ossOption.accessKeyId = info.accesskeyid;
                  that.ossOption.accessKeySecret = info.accesskeysecret;
                  that.ossOption.stsToken = info.securitytoken;
                  console.log(that.ossOption)
              }
          });
      },
      progress (done) {
            return function (done) {
                done();
            };
      },
      progress_en (p) {
            return function (done) {
                done();
            };
      },
      getNowFormatDate () { //  给上传的视频重命名为当前时间
          let date = new Date();
          let seperator1 = "-";
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          let strDate = date.getDate();
          if (month >= 1 && month <= 9) {
            month = "0" + month;
          }
          if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
          }
          let currentdate = year + seperator1 + month + seperator1 + strDate;
          return currentdate;
      },
      // 删除视频
      delVideo () {
          let that = this;
          that.fileList = [];
          that.form.video = '';

//          document.getElementById('uploadVideo').outerHTML = ''// 清空文件选择器;
      },
      // 删除视频
      delVideo_en () {
          let that = this;
          that.fileList_en = [];
          that.form.video_en = '';
          that.progressBar_en=0;
          //   var obj = document.getElementById("uploadVideo_en") ;
          // obj.outerHTML = obj.outerHTML;
         // document.getElementById('uploadVideo_en').outerHTML = ''// 清空文件选择器;
      },
      // 富文本编辑器
      editor(){
        let CKEDITOR = window.CKEDITOR;
        myEditor = CKEDITOR.replace("desc");
        myEditor_en = CKEDITOR.replace("desc_en");
        myEditor.setData("");
        myEditor_en.setData("");
      },
    }
  }
</script>
<style lang="less" scope>
  .el-form-item__content,.el-form-item__label{line-height:28px;}
  .el-upload-list__item-name [class^=el-icon]{height:auto!important;}
  .el-form-item__content{margin-left:78px;}
  .el-upload-list{width: 600px;}
  .el-upload-list__item-status-label{top:5px;}
  .container{
    font-size:14px;color:#333;
    padding: 20px;
    .iptFormLen{
      width: 600px;
    }
    .v-des{line-height:24px;padding:0 8px;margin-top:10px;font-size:12px;color:#999;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;}
    .video-list{width:600px;
       .v-des{color:#333;display:flex;justify-content: flex-start; align-items: center;}
       .el-icon-circle-check{margin-left:10px;cursor:pointer;color:#67c23a;display:block;}
       .el-icon-close{margin-left:10px;cursor:pointer; display:none;}
       .v-des:hover{background:#eee;}
       .v-des:hover .el-icon-circle-check{display:none;}
       .v-des:hover .el-icon-close{display:block;}
    }
    .v-upload-btn{width:80px;height:28px;position:relative;
      .file{width:80px;height:28px;position:absolute;top:0; left:0;cursor: pointer;opacity:0;}
    }
    .barProg{width: 200px;height:2px;}
    .progress{height:2px;background:#409EFF;
      -webkit-border-radius:1px;
      -moz-border-radius:1px;
      border-radius:1px;}
    .thumb{width:150px;height:100px;}
  }
</style>